package com.hy.quartz.config;

import com.hy.quartz.simple.SimpleTask;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * author: Mr.Du
 * Date: 2023/6/13
 * Time: 13:59
 */
@Configuration
@RequiredArgsConstructor
public class TaskConfig {
    
    public static final String SIMPLE_TASK = "simple-task";
    private final SchedulerFactoryBean schedulerFactoryBean;
    
    /**
     * 动态添加任务
     * @throws SchedulerException
     */
    @PostConstruct
    public void init() throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        boolean exists = scheduler.checkExists(JobKey.jobKey(SIMPLE_TASK));
        if (!exists) {
            scheduler.scheduleJob(jobDetail(), trigger());
        }
    }
    
    
    //@Bean
    public JobDetail jobDetail(){
        return JobBuilder.newJob(SimpleTask.class)
                .withIdentity("simple-task")
                .withDescription("简单任务")
                .storeDurably()
                .build();
    }
    
    //@Bean
    public Trigger trigger(){
        // 秒 分 时 日 月 周 [年]
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ? *");
        return TriggerBuilder.newTrigger()
                .withIdentity("simple-task-trigger")
                .forJob(jobDetail())
                .withSchedule(cronScheduleBuilder)
                .build();
    }
}
